﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SettingController.cs" company="ecblog.codeplex.com">
//   emrecoskun.net - ibrahimatay.com
// </copyright>
// <summary>
//   The Setting controller
// </summary>
// --------------------------------------------------------------------------------------------------------------------
 
namespace EcBlog.Areas.Admin.Controllers
{
    using System;
    using System.ComponentModel.Composition;
    using System.Globalization;
    using System.Linq;
    using System.Threading;
    using System.Web.Mvc;

    using EcBlog.Data;
    using EcBlog.Models;
    using EcBlog.Properties;

    using Elmah;

    using Telerik.Web.Mvc;
    using Telerik.Web.Mvc.Extensions;

    /// <summary>
    /// The Setting controller
    /// </summary>
    [Export, PartCreationPolicy(CreationPolicy.NonShared)]
#if !(DEBUG)
    [Filters.Authorize(PortalRole.Admin)]
#endif
    public class SettingController : Controller
    {
        #region ctor
        private readonly IEcUnitOfWork unitOfWork;

        /// <summary>
        /// Initializes a new instance of the <see cref="SettingController"/> class.
        /// </summary>
        /// <param name="unitOfWork">The unit of work.</param>
        [ImportingConstructor]
        public SettingController(IEcUnitOfWork unitOfWork)
        {
            this.unitOfWork = unitOfWork;
        } 
        #endregion

        #region Core Action Methods

        /// <summary>
        /// Gets the index view.
        /// </summary>
        /// <returns>The index view</returns>
        public ActionResult Index()
        {
            return this.View();
        } 
        #endregion

        #region AJAX User Master Grid Action Methods
        /// <summary>
        /// Lists the specified command.
        /// </summary>
        /// <param name="command">The command.</param>
        /// <returns>The list</returns>
        [GridAction(EnableCustomBinding = true)]
        public ActionResult List(GridCommand command = null)
        {
            if (command == null)
            {
                command = new GridCommand();
            }

            var setupKey = Enum.GetName(typeof(SiteSettingKey), SiteSettingKey.SetupCompleted);
            var list = this.unitOfWork.SiteSettingRepository.Get().Where(c => c.SettingKey.ToLower() != setupKey.ToLower());
            return this.View(list.ToGridModel(command.Page, command.PageSize, command.SortDescriptors, command.FilterDescriptors, command.GroupDescriptors));
        }

        /// <summary>
        /// Updates the specified setting.
        /// </summary>
        /// <param name="setting">The setting.</param>
        /// <param name="command">The command.</param>
        /// <returns>The list</returns>
        [HttpPost, GridAction(EnableCustomBinding = true)]
        public ActionResult Update(SiteSetting setting, GridCommand command = null)
        {
            if (this.ModelState.IsValid)
            {
                try
                {
                    var settingEntity  = this.unitOfWork.SiteSettingRepository.Get().First(s => s.SettingKey == setting.SettingKey);
                    settingEntity.SettingValue = setting.SettingValue;
                    this.unitOfWork.SiteSettingRepository.Update(settingEntity);
                    this.unitOfWork.Save();

                    if (setting.SettingKey == Enum.GetName(typeof(SiteSettingKey), SiteSettingKey.Culture))
                    {
                        this.ChangeCulture(setting.SettingValue);
                    }
                }
                catch (Exception e)
                {
                    ErrorSignal.FromCurrentContext().Raise(e);
                    this.Response.StatusCode = 500;
                    this.Response.AppendHeader(
                        "message", string.Format(ModelLocalization.SaveUnitOfWorkError, setting.SettingKey, e.Message));
                }
            }

            return this.List(command);
        }
        #endregion

        #region disbose

        /// <summary>
        /// Releases unmanaged resources and optionally releases managed resources.
        /// </summary>
        /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
        protected override void Dispose(bool disposing)
        {
            this.unitOfWork.Dispose();
            base.Dispose(disposing);
        }

        #endregion

        private void ChangeCulture(string cultureName)
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(cultureName);
            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(cultureName);
        } 
    }
}
